﻿using System;
using System.Collections.Generic;
using System.Text;
using ilibrary.source.model;
using DejaVuTocReader;

namespace DJVUHandler
{
    public class DJVUEbook : EBook
    {
        public DJVUEbook(int id, string filepath):base(id,filepath)
        {
            //on vérifie que c'est bien un fichier DJVU
            if (filepath == null || System.IO.Path.GetExtension(filepath).ToLower() != ".djvu")
                throw new NotSupportedException("The file " + filepath + " is not a DU file.");

        }

        public override bool readToc(IEBookReadingHandler cB)
        {
            try
            {
                if (DejaVuTocReader.DejaVuTocReader.HasToc(this.Filepath))
                {
                    string res = buildTOC(DejaVuTocReader.DejaVuTocReader.ReadToc(this.filePath), cB);
                    toc = "<toc>" + res + "</toc>";

                    return true;
                }
                else
                {

                    toc = string.Empty;//so that, we don't retry to load the toc
                    return false;
                }
            }
            catch (Exception)
            {
                toc = null; //no toc available
                return false;
            }
        }

        private string buildTOC(Bookmark bm, IEBookReadingHandler cB)
        {
            string res = "";

            res += "<tocItem>";
            res += "<topic>" + bm.getDisplayName() + "</topic>";
            if (bm.getChildren().Count > 0)
            {
                res += "<toc>";

                foreach (Bookmark mark in bm.getChildren())
                {

                    res += buildTOC(mark, cB);

                    if (cB != null)
                        cB.performReadingStep();

                }
                res += "</toc>";
            }
            res += "</tocItem>";
            return res;
        }
    }
}
